package com.hyt.it.ogt.kq.common.gov.progress;

import com.hyt.exception.exception.BusinessRequestException;
import com.hyt.progress.creator.anno.ProgressAnno;
import com.hyt.progress.creator.policy.ProgressLockKeyCreator;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.CodeSignature;
import org.aspectj.lang.reflect.MethodSignature;

import java.util.Objects;

/**
 * @PACKAGE_NAME: com.hyt.it.ogt.kq.common.gov.progress
 * @USER: Wuyingge
 * @DATE: 2023/10/10 09:58
 * @PROJECT_NAME: it-ogt-kq
 * @Desc :
 **/
public class ImportCandidatePhotoLockKeyCreator implements ProgressLockKeyCreator {

    public static final String LOCK_PARAM_FIELD = "taskId";

    private Object getFiledValueOrThrow(ProceedingJoinPoint pjp, ProgressAnno progressAnno) {
        String[] parameterNames = ((CodeSignature) pjp.getSignature()).getParameterNames();
        Object[] args = pjp.getArgs();
        for (int i = 0; i < parameterNames.length; i++) {
            if (Objects.equals(parameterNames[i], LOCK_PARAM_FIELD)) {
                return args[i];
            }
        }
        throw new BusinessRequestException(progressAnno.errorCode(), "传参必须有指定的锁定字段");
    }

    @Override
    public String createLockKey(ProceedingJoinPoint pjp, ProgressAnno progressAnno) {
        String className = pjp.getTarget().getClass().getName();
        String methodName = ((MethodSignature) pjp.getSignature()).getMethod().getName();
        // 根据字段锁定
        Object fieldValue = getFiledValueOrThrow(pjp, progressAnno);
        return className + methodName + fieldValue.toString();

    }
}
